<script setup>
import { addRoleListAPI, deleteRoleListAPI, getRoleListAPI, updateRoleListAPI, updateRoleStatusAPI, setRoleRulesAPI } from '@/api/role'
import { ref, nextTick } from 'vue'
import FormDrawer from '@/components/FormDrawer.vue'
import { useInitTable, useInitForm } from '@/composables/useCommon'
import ListHeader from '@/components/ListHeader.vue'
import { getRuleListAPI } from '@/api/rule'
import { toast } from '@/composables/util'
const {
  tableData,
  loading,
  total,
  currentPage,
  handleDelete,
  getData,
  handleStatusChange
} = useInitTable({
  getList: getRoleListAPI,
  delete: deleteRoleListAPI,
  updateStatus: updateRoleStatusAPI

})
const {
  form,
  rules,
  formDrawerRef,
  formRef,
  drawerTitle,
  handleEdit,
  handleSubmit,
  handleCreate,
} = useInitForm(
  {
    form: {
      name: '',
      desc: '',
      status: 1
    },
    rules: {
      name: [
        { required: true, message: '角色名称不能为空', trigger: 'blur' }
      ],
      desc: [
        { required: true, message: '角色名称不能为空', trigger: 'blur' }
      ],
    },
    getData,
    update: updateRoleListAPI,
    add: addRoleListAPI
  }
)

const handleCurrentChange = (val) => {
  currentPage.value = val
  getData(currentPage.value)
}

const setRuleFormDrawerRef = ref(null)
const ruleList = ref([])
const treeHeight = ref(0)
const roleId = ref(0)
const defaultExpandedKeys = ref([])
const elTreeRef = ref(null)
// 当前用户拥有的权限id
const ruleIds = ref([])
const checkStrictly = ref(false)

const openSetRule = async (row) => {
  roleId.value = row.id
  treeHeight.value = window.innerHeight - 180
  checkStrictly.value = true
  const res = await getRuleListAPI(1)
  ruleList.value = res.list
  defaultExpandedKeys.value = res.list.map(o => o.id)
  setRuleFormDrawerRef.value.openDrawer()

  //当前角色拥有的权限id
  // console.log(row.rules.map(o => o.id));
  ruleIds.value = row.rules.map(o => o.id)
  // 这里使用nextTick 等待elTreeRef渲染完毕
  nextTick(() => {
    // console.log(elTreeRef.value);
    elTreeRef.value.setCheckedKeys(ruleIds.value)
    checkStrictly.value = false
  })


}
const handleSetRuleSubmit = async () => {
  setRuleFormDrawerRef.value.showLoading()
  const res = await setRoleRulesAPI(roleId.value, ruleIds.value)
  toast('配置成功')
  setRuleFormDrawerRef.value.hideLoading()
  getData()
  setRuleFormDrawerRef.value.closeDrawer()


}
const handleTreeCheck = (...e) => {
  // console.log(e);
  const { checkedKeys, halfCheckedKeys } = e[1]
  ruleIds.value = [...checkedKeys, ...halfCheckedKeys]
}
</script>
<template>
  <el-card shadow="never" class="border-0">
    <ListHeader @create="handleCreate" @refresh="getData"></ListHeader>
    <el-table v-loading="loading" border :data="tableData" stripe style="width: 100%">
      <el-table-column prop="name" label="角色名称" />
      <el-table-column prop="desc" label="角色描述" width="380" />
      <el-table-column label="状态" align="center" width="120">
        <template #default="{ row }">
          <el-switch :disabled="row.super === 1" :loading="row.statusLoading" :model-value="row.status"
            :active-value="1" :inactive-value="0" @change="handleStatusChange($event, row)" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" text @click="openSetRule(scope.row)">配置权限</el-button>
          <el-button type="primary" size="small" text @click="handleEdit(scope.row)">修改</el-button>
          <el-popconfirm title="是否要删除该公告" confirm-button-text="确认" cancel-button-text="取消"
            @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button type="primary" size="small" text>删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class="flex items-center justify-center mt-5">
      <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" background
        layout="prev, pager,next" :total="total" />
    </div>
    <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">
      <el-form :model="form" ref="formRef" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="desc">
          <el-input v-model="form.desc" placeholder="请输入角色描述" type="textarea" :rows="5"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
    </FormDrawer>

    <!-- 权限配置 -->
    <FormDrawer ref="setRuleFormDrawerRef" title="权限配置" @submit="handleSetRuleSubmit">
      <el-tree-v2 :check-strictly="checkStrictly" ref="elTreeRef" node-key="id"
        :default-expanded-keys="defaultExpandedKeys" :data="ruleList" :props="{ label: 'name', children: 'child' }"
        show-checkbox :height="treeHeight" @check="handleTreeCheck">
        <template #default="{ node, data }">
          <div class="flex items-center">
            <el-tag :type="data.menu ? 'primary' : 'info'" size="small">{{ data.menu ? '菜单' : '权限' }}</el-tag>
            <span class="ml-2 text-sm">{{ data.name }}</span>
          </div>
        </template>
      </el-tree-v2>
    </FormDrawer>
  </el-card>
  <!-- 新增|刷新 -->
</template>